/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Jiang Jinxi
 * Date: 2024-03-27
 * Time: 20:44
 */
public class HashBuck {

    public class Node{
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }
    public Node[] arr = new Node[10];
    public int usedSize;
    public static final double LOAD_FACTOR = 0.75;

    public void push(int key,int val){
        Node node = new Node(key,val);
        int index = key % arr.length;
        Node cur = arr[index];
        while(cur != null){
            if(cur.key == key){
                cur.val = val;
                return ;
            }
            cur = cur.next;
        }
        node.next = arr[index];
        arr[index] = node;

        usedSize++;
        if(doLoadFactor() >= LOAD_FACTOR){
            reSize();
        }
    }
    private double doLoadFactor(){
        return usedSize*1.0 / arr.length;
    }
    private void reSize(){
        Node[] newArray = new Node[arr.length * 2];
        for (int i = 0; i < arr.length; i++) {
            Node cur = arr[i];
            while(cur != null){
                int index = cur.key % newArray.length;
                Node curNext = cur.next;
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curNext;
            }
        }
        arr = newArray;
    }

    public int getVal(int key){
        int index = key % arr.length;
        Node cur = arr[index];
        while(cur != null){
            if(cur.key == key){
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
